<template>
	<view class="page-wrapper">
	    <image :src="deviceImg" mode="aspectFit" class="device-image" />
		<view class="model-list">
			<up-button type="primary" :plain="activeType!=ModelMap.INTERVAL" @click.stop="changeActiveType(ModelMap.INTERVAL)" 
				shape="circle" text="间歇模式"></up-button>
			<up-button type="primary" :plain="activeType!=ModelMap.RADAR" @click.stop="changeActiveType(ModelMap.RADAR)" 
				shape="circle" text="雷达模式"></up-button>
		</view>
		
		<view class="chart-list">
			<view class="chart-item">
				<view class="chart-item-title">
					<text>水量</text>
					<uni-icons type="refreshempty" size="30" :style="`transform: rotate(${rotateDeg}deg);`" class="animation" @click="refreshData"></uni-icons>
				</view>
				<up-line-progress :percentage="percentData.water" :active-color="formatColor(percentData.water)"></up-line-progress>				
			</view>
			<view class="chart-item">
				<view class="chart-item-title">
					<text>水质</text>
					<view>
						<up-tag shape="circle" size="mini" text="优良" v-if="percentData.quality>=80" type="success"></up-tag>
						<up-tag shape="circle" size="mini" text="中等" v-else-if="percentData.quality>=50" type="info"></up-tag>
						<up-tag shape="circle" size="mini" text="较差" v-else-if="percentData.quality>=20" type="warning"></up-tag>
						<up-tag shape="circle" size="mini" text="危险" v-else type="error"></up-tag>
					</view>					
				</view>
				<up-line-progress :percentage="percentData.quality" :active-color="formatColor(percentData.quality)" :showText="false"></up-line-progress>				
			</view>
			<view class="chart-item">
				<view class="chart-item-title">
					<text>电量</text>
				</view>
				<up-line-progress :percentage="percentData.power" :active-color="formatColor(percentData.power)"></up-line-progress>				
			</view>
		</view>
		
		<view class="bottom-box">
		    <up-button :text="openStatus?'关闭饮水机':'打开饮水机'" size="normal" :icon="openStatus?'pause':'play-right'"
				type="primary" :plain="openStatus" style="width: 620rpx;" shape="circle" @click.stop="toggleOpenSatus"></up-button>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref, } from 'vue';
import { onLoad, onShow, } from '@dcloudio/uni-app'
import { getClockListApi, changeWeiShiApi, } from "@/api/request";
import { CacheUtils, debounceFunction, navigateToUniPage, } from '@/utils/index';
import { useI18n } from 'vue-i18n';

const ModelMap = {
	RADAR: 1, 		// 雷达模式
	INTERVAL: 0, 	// 间隔模式
}
const { t } = useI18n();
const deivceId = ref('');
const deviceImg = ref('');
const activeType = ref(ModelMap.INTERVAL);
const openStatus = ref(false);
const rotateDeg = ref(0); // 旋转角度
// @Test-change
const percentData = reactive({
	power: 80,		// 电量
	water: 90,		// 水量
	quality: 80, 	// 水质
});
const config = {
	MAX_SECONDS: 30, // 初始最大毫秒数
}
const timerLeft = ref(config.MAX_SECONDS);
const timer = ref(null);

// 进度条颜色格式化
const formatColor = (val)=>{
	const num = Number(val);
	if(num>=70){
		return '#19be6b';
	}
	if(num>=50){
		return '#82848a';
	}	
	if(num>=20){
		return '#f29100';
	}
	
	return '#dd6161';
}

const resetTimer = ()=>{
	uni.hideLoading();
	clearInterval(timer.value);
	timer.value = null;
	timerLeft.value = config.MAX_SECONDS;
}

const changeActiveType = (type)=>{
	if(type==activeType.value){
		return;
	}
	// activeType.value = type;
	
	uni.showLoading({
		title: '请求中...'
	});
	uni.$emit('reqWaterModel', type);
	timer.value = setInterval(()=>{
		timerLeft.value--;
		if(timerLeft.value<=0){			
			resetTimer();
			uni.showModal({
				title: '操作异常',
				content: '设置饮水机模式失败,请确保饮水机连接成功',
				showCancel: false,
			});
		}
	}, 1000);
}

const toggleOpenSatus = ()=>{
	uni.showLoading({
		title: '请求中...'
	});
	uni.$emit('reqWaterOpenChange', !openStatus.value);
	timer.value = setInterval(()=>{
		timerLeft.value--;
		if(timerLeft.value<=0){			
			resetTimer();
			uni.showModal({
				title: '操作异常',
				content: '设置饮水机开关失败,请确保饮水机连接成功',
				showCancel: false,
			});
		}
	}, 1000);
}


const refreshData = ()=>{
	rotateDeg.value = 360;
	uni.showLoading({
		title: '加载中...'
	});
	uni.$emit('reqWaterInfo');
	setTimeout(()=>{
		uni.hideLoading();
		rotateDeg.value = 0;
	}, 2000);
}

// @Test-todo
const listenUniEvent = ()=>{
	// 返回喂水器信息
	uni.$on("resWaterInfo", (resultCmd) => {
		// 返回数据案例: '55aaa405 3c 50 01 00 08 34ab'
		const validPart = String(resultCmd).slice(8, -4);
		if(validPart.length!==10){
			uni.showToast({
				title: '信息格式不合法',
				icon: 'error'
			});
		}else{
			const [ waterStr, powerStr, modelStr, openStatusStr, qualityStr ] = [
				validPart.slice(0,2), validPart.slice(2,4), validPart.slice(4,6), validPart.slice(6,8), validPart.slice(8,10)];
			const powserNum = parseInt(powerStr,16), waterNum = parseInt(waterStr,16), qualityNum = parseInt(qualityStr, 16), modelNum = parseInt(modelStr, 16);
			percentData.power = powserNum;
			percentData.water = waterNum;
			percentData.quality = qualityNum;
			activeType.value = (modelNum==1?ModelMap.RADAR:ModelMap.INTERVAL);
			openStatus.value = openStatusStr=='01'?true:false;
		}
	});
	
	// 返回喂水器模式切换的响应结果
	uni.$on('resWaterModel', (resultCmd) => {
		// 返回数据案例: '55aaa20101ab'
		const validPart = String(resultCmd).slice(8, 10);
		console.log(resultCmd, '切换喂水器模式返回结果');
		if(validPart=='01'){
			activeType.value = ModelMap.RADAR;
		}else{
			activeType.value = ModelMap.INTERVAL;
		}
		// 根据返回结果设置模式
		resetTimer();
	});
	
	// 返回喂水器开关切换的响应结果
	uni.$on('resWaterOpenChange', (resultCmd) => {
		// 返回数据案例: '55aaa10101ab'
		const validPart = String(resultCmd).slice(8, 10);
		console.log(validPart, '切换喂水器开关返回结果');
		if(validPart=='01'){
			openStatus.value = true;
		}else{
			openStatus.value = false;
		}
		// 根据返回结果设置模式
		resetTimer();
	});
}



onLoad((query) => {
    uni.setNavigationBarTitle({
        title: query.title
    });
    deivceId.value = query.imei;
	deviceImg.value = decodeURIComponent(query.img); 
	refreshData();
	listenUniEvent();
})

onShow(()=>{	
	// setInterval(refreshData, 10000);
})
</script>

<style lang="scss" scoped>
$bottom-height: 100rpx;

.page-wrapper {
    padding-bottom: $bottom-height;
}

.bottom-box {
    bottom: 0rpx;
    left: 0rpx;
    right: 0rpx;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    height: $bottom-height;
    box-sizing: border-box;
    background-color: #FFFFFF;
}
	
.device-image {
	display: block;
	width: 380rpx;
	height: 380rpx;
	margin: 60rpx auto;
	margin-bottom: 40rpx;
}

.model-list{
	display: flex;
	column-gap: 20rpx;
	padding: 40rpx 60rpx;
}

.chart-list{
	padding: 40rpx 40rpx;
	display: flex;
	flex-direction: column;
	row-gap: 40rpx;
	.chart-item{
		.chart-item-title{
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 6rpx;
		}
	}
}

.animation{
	transform-origin: center;
	transition: transform ease 0.4s;
}

</style>